import { View, Text, Button } from "@tarojs/components";
import { AtSteps, AtFloatLayout } from "taro-ui";
import Distribution from "./components/Distribution";
import { useEffect, useState } from "react";
import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui";
import GoodsList from "./components/GoodsList";
import Remarks from "./components/remarks";
import { AtInput, AtForm, AtRadio } from "taro-ui";
import Taro from "@tarojs/taro";
import { AtMessage } from "taro-ui";
import "./index.scss";
import { AtToast } from "taro-ui";
import { createOrder } from "../../api/order/index";
import { connect } from "react-redux";
import { addAddress, getAddressList } from "../../api/address/index";
const stepBarList = [
  { title: "创建订单" },
  { title: "商家接收" },
  { title: "配送" },
  { title: "售后服务" }
];

type addressType = {
  ownerId: number;
  detaileAddress: string;
  phone: string;
  tag: string;
  consigneeName: number;
};

type addressTagType = { label: string; value: number; desc: string };

const index = props => {
  const [isOpened, SetIsOpened] = useState<boolean>();
  const [isOpenedAddress, SetIsOpenedAddress] = useState<boolean>();
  const [detailMessage, SetDetailMessage] = useState<String | number>();
  const [phone, SetPhone] = useState<String>();
  const [consignee, SetConsignee] = useState<String>();
  const [addressList, SetAddressList] = useState<addressTagType[]>();
  const [addressFlag, SetAddressFlag] = useState<number>();
  const [selectAddress, SetSelectAddress] = useState<string>();
  const [allPrice, SetAllPrice] = useState<number>();
  const [remark, SetRemark] = useState<string>();
  const [expressDate, SetExpressDate] = useState<string>();
  const [tag, SetTag] = useState<string>();
  const [onpenToast, SetOpenToast] = useState<boolean>();
  const restInfo = () => {
    SetDetailMessage("");
    SetPhone("");
    SetConsignee("");
    SetTag("");
  };

  const getAllPrice = (price: number) => {
    SetAllPrice(price);
  };

  const getRemark = (remark: string) => {
    SetRemark(remark);
  };
  const initData = () => {
    getAddressList().then(resp => {
      const list = [];
      console.log(resp);

      resp.map(item => {
        list.push({
          label: item.detailedAddress,
          value: item.addressId,
          desc: item.consigneeName + "-" + item.phone
        });
      });

      SetAddressList(list);
    });
  };

  const getExpressDate = (str: string) => {
    SetExpressDate(str);
  };

  useEffect(() => {
    initData();
  }, []);

  const submit = () => {
    const goodsList = [];

    if (!addressFlag || !expressDate) {
      Taro.atMessage({
        message: "请选择收获地址与配送时间"
      });
      return;
    }

    props.cart.map(item => {
      console.log(item);

      goodsList.push({
        num: item.count,
        price: item.price,
        goodsId: item.id,
        stockId: item.stockId,
        goodsName: item.title,
        picture: item.picture
      });

      props.dispatch({
        type: "cart/pushData",
        payload: {
          id: item.id
        }
      });
    });

    const dataWrapper = {
      ownder: 0,
      allPrice: allPrice,
      goodsList: goodsList,
      addressId: addressFlag,
      remark: expressDate + "       " + (remark ? remark : "")
    };
    console.log(dataWrapper);

    createOrder(dataWrapper).then(resp => {
      SetOpenToast(true);
      setInterval(() => {
        Taro.switchTab({
          url: "/pages/mine/index"
        });
      }, 2000);
    });
  };

  return (
    <View className="create_order_wrapper">
      <AtMessage />
      <AtToast
        isOpened={onpenToast}
        text="订单创建并支付成功"
        icon="heart-2"
      ></AtToast>
      {/* 步骤条 */}
      <View className="stepbar">
        <View className="stepbar_wrapper">
          <AtSteps items={stepBarList} current={0} onChange={() => {}} />
        </View>
      </View>

      {/* 配送信息 */}
      <View className="distribution_information">
        <View
          className="distribution_information_title"
          onClick={() => {
            SetIsOpened(true);
          }}
        >
          <Text style={{ color: "#f18108", fontWeight: 600, fontSize: 17 }}>
            {selectAddress ? selectAddress : "请选择收货地址"}
          </Text>
          <View
            className="at-icon at-icon-chevron-right"
            style={{ color: "#f18108" }}
          ></View>
        </View>
        <View>
          <Distribution getExpressDate={getExpressDate} />
        </View>
        {/* 选择收获地址 */}
        <AtFloatLayout
          isOpened={isOpened}
          title="收货地列表"
          onClose={() => {
            SetIsOpened(!isOpened);
          }}
        >
          <View
            className="add_address"
            onClick={() => {
              SetIsOpenedAddress(true);
            }}
          >
            添加收货地
          </View>
          <View style={{ overflow: "hidden", overflowY: "scroll" }}>
            {addressList && (
              <AtRadio
                options={addressList}
                value={addressFlag}
                onClick={value => {
                  SetAddressFlag(value);
                  addressList.forEach(item => {
                    if (item.value == value) {
                      SetSelectAddress(item.label);
                    }
                  });
                }}
              />
            )}
          </View>
        </AtFloatLayout>
      </View>
      {/* 商品信息 */}
      <View>
        <GoodsList cart={props.cart} getAllPrice={getAllPrice} />
      </View>
      {/* 备注 */}
      <View>
        <Remarks getRemark={getRemark}></Remarks>
      </View>
      {/* 创建订单 */}
      <View className="create_wrapper">
        <View style={{ marginLeft: 10 }}>￥{allPrice}</View>
        <View className="create_buuton" onClick={submit}>
          提交订单
        </View>
      </View>
      {/* 添加地址 */}

      <AtModal isOpened={isOpenedAddress}>
        <AtModalHeader>标题</AtModalHeader>
        <AtModalContent>
          <AtInput
            name="value"
            title="详细地址"
            type="text"
            placeholder="请输入详细地址"
            value={detailMessage}
            onChange={value => {
              SetDetailMessage(value);
            }}
          />
          <AtInput
            name="value"
            title="收货人"
            type="text"
            placeholder="请输入收货人姓名"
            value={consignee}
            onChange={value => {
              SetConsignee(value);
            }}
          />
          <AtInput
            name="value"
            title="收货人手机号"
            type="phone"
            placeholder="请输入收货人手机号"
            value={phone}
            onChange={value => {
              SetPhone(value);
            }}
          />
          <AtRadio
            options={[
              { label: "公司", value: "1" },
              { label: "家", value: "2" },
              { label: "学校", value: "3" },
              { label: "其他", value: "4" }
            ]}
            value={tag}
            onClick={value => {
              SetTag(value);
            }}
          />
        </AtModalContent>
        <AtModalAction>
          {" "}
          <Button
            onClick={() => {
              SetIsOpenedAddress(false);
            }}
          >
            取消
          </Button>{" "}
          <Button
            onClick={() => {
              if (!detailMessage) {
                Taro.atMessage({
                  message: "请输入详细地址",
                  type: "error"
                });
                return;
              }
              if (!phone) {
                Taro.atMessage({
                  message: "请输入用户手机号",
                  type: "error"
                });
                return;
              }
              if (!consignee) {
                Taro.atMessage({
                  message: "请输入接收人",
                  type: "error"
                });
                return;
              }
              if (!tag) {
                Taro.atMessage({
                  message: "请选择标签",
                  type: "error"
                });
                return;
              }

              const data = {
                ownerId: 0,
                detailedAddress: detailMessage,
                phone: phone,
                tag: tag,
                consigneeName: consignee
              };
              addAddress(data).then(() => {
                SetIsOpenedAddress(false);
                Taro.atMessage({
                  message: "添加成功",
                  type: "success"
                });
                restInfo();
                initData();
              });
            }}
          >
            确定
          </Button>{" "}
        </AtModalAction>
      </AtModal>
    </View>
  );
};
export default connect(({ cart }) => ({ cart }))(index);
